<template>
  <div
    class="widget-view widget_flex_container"
    :class="{
      active: selectWidget.key == element.key,
    }"
    @click.stop="handleSelectWidget"
  >
    <div
      v-if="element.options.showLabel"
      class="widget_flex_title el-form-item__label"
    >
      {{ element.name + ':' }}
    </div>
    <div class="flex_container">
      <div
        v-for="(column, columnIndex) in element.columns"
        :key="`${element.key}$${columnIndex}`"
        class="sub_form"
      >
        <div v-if="element.options.showSubLabel" class="sub_form_title">
          {{ element.name + (index + 1) }}
        </div>
        <div class="sub_form_body">
          <draggable
            v-model="column.list"
            :no-transition-on-drag="true"
            v-bind="{
              group: 'widgets',
              ghostClass: 'ghost',
              animation: 200,
              handle: '.drag-widget',
            }"
            @end="handleMoveEnd"
            @add="handleWidgetAdd($event, element, columnIndex)"
          >
            <transition-group name="fade" tag="div" class="widget-tab-list">
              <template v-for="(el, i) in column.list">
                <widget-form-item
                  :key="el.key"
                  v-if="el.key"
                  :element="el"
                  :select.sync="selectWidget"
                  :index="i"
                  :data="column"
                />
              </template>
            </transition-group>
          </draggable>
        </div>
        <div
          v-if="element.options.operational && !element.options.disabled"
          class="flex_container_operation"
        >
          <el-button type="text" @click="del(columnIndex)">
            <i class="el-icon el-icon-delete"></i>
          </el-button>
        </div>
      </div>
      <div
        v-if="element.options.operational && !element.options.disabled"
        class="widget_flex_operation"
      >
        <el-button type="text" @click="add">
          {{ $t('fm.actions.add') }}
        </el-button>
      </div>
    </div>
    <div
      v-if="selectWidget.key == element.key"
      class="widget-view-drag widget-tabs-drag"
    >
      <i class="iconfont icon-drag drag-widget" />
    </div>
    <div
      v-if="selectWidget.key == element.key"
      class="widget-view-action widget-tabs-action"
    >
      <i class="iconfont icon-trash" @click.stop="handleWidgetDelete(index)" />
    </div>
  </div>
</template>

<script>
import Draggable from 'vuedraggable'
import WidgetFormItem from './WidgetFormItem'

import {
  basicComponents,
  layoutComponents,
  advanceComponents,
} from '../configs/componentsConfig.js'

export default {
  components: {
    Draggable,
    WidgetFormItem,
  },
  props: {
    element: {
      type: Object,
    },
    select: {
      type: Object,
    },
    index: {
      type: Number,
    },
    data: {
      type: Object,
    },
  },
  data() {
    return {
      basicComponents,
      layoutComponents,
      advanceComponents,
      selectWidget: this.select,
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.selectWidget = this.element
    })
  },
  methods: {
    handleWidgetDelete(index) {
      if (this.data.list.length - 1 === index) {
        if (index === 0) {
          this.selectWidget = {}
        } else {
          this.selectWidget = this.data.list[index - 1]
        }
      } else {
        this.selectWidget = this.data.list[index + 1]
      }

      this.$nextTick(() => {
        this.data.list.splice(index, 1)
      })
    },
    handleMoveEnd() {},
    handleWidgetAdd(evt, element, index) {
      console.log('add', evt)
      console.log('end', evt)
      const newIndex = evt.newIndex
      const to = evt.to
      console.log(to)

      //为拖拽到容器的元素添加唯一 key
      const key =
        Date.parse(new Date()) + '_' + Math.ceil(Math.random() * 99999)

      let tmp = {
        ...element.columns[index].list[newIndex],
        options: {
          ...element.columns[index].list[newIndex].options,
          remoteFunc: 'func_' + key,
        },
        key,
        // 绑定键值
        model: element.columns[index].list[newIndex].type + '_' + key,
        rules: [],
      }

      if (
        element.columns[index].list[newIndex].type === 'radio' ||
        element.columns[index].list[newIndex].type === 'checkbox' ||
        element.columns[index].list[newIndex].type === 'select' ||
        element.columns[index].list[newIndex].type === 'refusecode'
      ) {
        tmp = {
          ...tmp,
          options: {
            ...tmp.options,
            options: tmp.options.options.map((item) => ({
              ...item,
            })),
          },
        }
      }

      if (element.columns[index].list[newIndex].type === 'grid') {
        this.$set(element.columns[index].list, newIndex, {
          ...element.columns[index].list[newIndex],
          columns: element.columns[index].list[newIndex].columns.map(
            (item) => ({
              ...item,
            })
          ),
        })
      }

      if (element.columns[index].list[newIndex].type === 'form') {
        const preWidgets = JSON.parse(
          JSON.stringify(element.columns[index].list.slice(0, newIndex))
        )
        const sufWidgets = JSON.parse(
          JSON.stringify(element.columns[index].list.slice(newIndex + 1))
        )

        tmp.form.list.forEach((formItem) => {
          const widget = this.generateWidget(formItem)
          preWidgets.push(widget)
        })
        this.$set(element.columns[index], 'list', [
          ...preWidgets,
          ...sufWidgets,
        ])
      } else {
        this.$set(element.columns[index].list, newIndex, tmp)
      }

      this.selectWidget = element.columns[index].list[newIndex]
    },
    handleSelectWidget() {
      this.selectWidget = this.element
    },
    generateWidget(widget) {
      let tmp = JSON.parse(JSON.stringify(widget))
      const key =
        Date.parse(new Date()) + '_' + Math.ceil(Math.random() * 99999)
      tmp = {
        ...tmp,
        key,
        model: `${tmp.type}_${key}`,
      }
      if (widget.type === 'tabs') {
        const tabs = tmp.tabs.map((item) => {
          const list = item.list.map((subItem) => {
            return this.generateWidget(subItem)
          })
          return {
            ...item,
            list,
          }
        })
        tmp.tabs = tabs
      } else if (widget.type === 'grid' || widget.type === 'flexContainer') {
        const columns = tmp.columns.map((item) => {
          const list = item.list.map((subItem) => {
            return this.generateWidget(subItem)
          })
          return {
            ...item,
            list,
          }
        })
        tmp.columns = columns
      }
      // const noModelLabels = ['blank', 'grid', 'tabs', 'flexContainer']
      return tmp
    },
    add() {},
    del() {},
  },
  watch: {
    select(val) {
      this.selectWidget = val
    },
    selectWidget: {
      handler(val) {
        this.$emit('update:select', val)
      },
      deep: true,
    },
    'element.tabs': {
      handler(val) {
        // if (!val.find((item) => item.name === this.element.options.active)) {
        //   this.element.options.active = val[0].name
        // }
      },
      deep: true,
    },
  },
}
</script>

<style lang="scss" scoped>
.widget_flex_container {
  padding: 10px 0;
  display: flex;
  &.active {
    outline-color: #e6a23c !important;
    border-color: #e6a23c !important;
  }
  .widget-view-drag,
  .widget-view-action {
    background: #e6a23c !important;
  }
  .widget-tab-list {
    min-height: 60px;
    background: none;
    border: 1px solid #ccc;
  }
  .flex_container {
    min-height: 50px;
    padding: 10px;
    flex: 1;
  }
  .widget_flex_title {
    font-size: 14px;
    padding: 10px 0 20px 20px;
  }
  .sub_form_title {
    font-size: 14px;
    color: #606266;
    padding-right: 10px;
  }
  .sub_form {
    position: relative;
    display: flex;
  }
  .sub_form_body {
    flex: 1;
  }
  .flex_container_operation {
    font-size: 18px;
    padding: 0 10px;
    .el-button {
      font-size: 16px;
    }
  }
}
</style>
